// admin_dashboard.js
// 初始化Socket.IO
const socket = io();

// 全局函数定义
window.viewFeedbackDetail = function(feedbackId) {
    fetch(`/api/feedbacks/${feedbackId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('无法加载反馈详情');
            }
            return response.json();
        })
        .then(data => {
            if (!data) {
                showNotification('错误', '反馈不存在');
                return;
            }

            let detailHTML = `
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">反馈详情</div>
                    </div>
                    <div class="card-content">
                        <p>${data.content}</p>
                    </div>
                    <div class="card-actions">
                        <p>提交用户: ${data.username}</p>
                        <p>提交时间: ${data.created_at}</p>
                        <p>状态: ${data.status === 'pending' ? '待处理' : '已处理'}</p>
                    </div>`;
            
            if (data.responses && data.responses.length > 0) {
                detailHTML += `
                    <div class="section-title" style="margin-top: 20px;">
                        <i class="fas fa-comment-dots"></i>
                        <span>处理回复</span>
                    </div>
                    <div class="card-content">
                        ${data.responses.map(r => `
                            <div class="response-item" style="background: rgba(255,255,255,0.1); padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                                <p>${r.content}</p>
                                <small>回复时间: ${r.created_at}</small>
                            </div>
                        `).join('')}
                    </div>`;
            }
            
            detailHTML += `
                    <div class="card-actions">
                        <button class="btn btn-success" onclick="respondToFeedback('${feedbackId}')">
                            <i class="fas fa-comment"></i> 回复
                        </button>
                    </div>
                </div>`;
            
            document.getElementById('feedbacks-list').innerHTML = detailHTML;
        })
        .catch(error => {
            showNotification('错误', '无法加载反馈详情');
            console.error('Error:', error);
        });
}

window.respondToFeedback = function(feedbackId) {
    const responseContent = prompt('请输入回复内容:');
    if (!responseContent) {
        showNotification('输入错误', '回复内容不能为空');
        return;
    }

    fetch('/api/feedback_responses', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
            feedback_id: feedbackId, 
            content: responseContent 
        }),
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(data => {
                throw new Error(data.message || '回复失败');
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            showNotification('操作成功', '回复已发送');
            // 重新加载反馈列表
            loadFeedbacks();
        } else {
            showNotification('操作失败', data.message || '回复失败');
        }
    })
    .catch(error => {
        showNotification('操作失败', error.message || '无法连接到服务器');
        console.error('Error:', error);
    });
}

window.approveAdminRequest = function(requestId) {
    console.log(`批准申请: ${requestId}`);
    
    fetch(`/api/admin_requests/${requestId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ status: 'approved' })
    })
    .then(response => {
        if (response.status === 404) {
            throw new Error('接口不存在');
        }
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            showNotification('操作成功', '申请已批准');
            loadAdminRequests();
        } else {
            const message = data?.message || '操作失败';
            showNotification('操作失败', message);
        }
    })
    .catch(error => {
        showNotification('操作失败', error.message || '无法连接到服务器');
        console.error('Error:', error);
    });
}

window.rejectAdminRequest = function(requestId) {
    console.log(`拒绝申请: ${requestId}`);
    
    fetch(`/api/admin_requests/${requestId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ status: 'rejected' })
    })
    .then(response => {
        if (response.status === 404) {
            throw new Error('接口不存在');
        }
        return response.json();
    })
    .then(data => {
        if (data && data.success) {
            showNotification('操作成功', '申请已拒绝');
            loadAdminRequests();
        } else {
            const message = data?.message || '操作失败';
            showNotification('操作失败', message);
        }
    })
    .catch(error => {
        showNotification('操作失败', error.message || '无法连接到服务器');
        console.error('Error:', error);
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 标签页切换
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');

            // 移除所有活动标签
            tabs.forEach(t => t.classList.remove('active'));

            // 添加当前活动标签
            this.classList.add('active');

            // 隐藏所有内容
            const contents = this.closest('.tabs').nextElementSibling.parentElement.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'));

            // 显示对应内容
            document.getElementById(`${tabId}-tab`).classList.add('active');
            
            // 如果切换到问卷回答标签，加载问卷回答
            if (tabId === 'survey-responses') {
                loadSurveyResponses();
            } 
            // 如果切换到反馈标签，加载反馈
            else if (tabId === 'feedbacks') {
                loadFeedbacks();
            }
            // 如果切换到管理员申请标签，加载申请
            else if (tabId === 'admin-requests') {
                loadAdminRequests();
            }
        });
    });

    // 显示通知
    function showNotification(title, content) {
        const notification = document.getElementById('notification');
        document.getElementById('notification-title').textContent = title;
        document.getElementById('notification-content').textContent = content;

        notification.classList.add('show');

        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    }

    // 加载公告
    function loadAnnouncements() {
        fetch('/api/announcements')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('announcements-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-bullhorn"></i>
                            <h3>暂无公告</h3>
                            <p>还没有发布任何公告</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(announcement => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">${announcement.title}</div>
                            <div class="card-date">${announcement.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${announcement.content}</p>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-danger" onclick="deleteAnnouncement('${announcement.id}')">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    `;
                    list.appendChild(card);
                });
            });
    }

    // 加载问卷
    function loadSurveys() {
        fetch('/api/surveys')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('surveys-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-poll"></i>
                            <h3>暂无问卷</h3>
                            <p>还没有发布任何问卷</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(survey => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">${survey.title}</div>
                            <div class="card-date">${survey.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${survey.content}</p>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-danger" onclick="deleteSurvey('${survey.id}')">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    `;
                    list.appendChild(card);
                });
            });
    }

    // 加载用户列表
    function loadUsers() {
        fetch('/api/users')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('users-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-users"></i>
                            <h3>暂无用户</h3>
                            <p>还没有任何用户</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(user => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">${user.username}</div>
                            <div class="card-date">${user.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>角色: ${user.role}</p>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-danger" onclick="deleteUser('${user.id}')">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    `;
                    list.appendChild(card);
                });
            });
    }

    // 加载反馈列表
    function loadFeedbacks() {
        fetch('/api/feedbacks')
            .then(response => {
                if (!response.ok) {
                    throw new Error('无法加载反馈');
                }
                return response.json();
            })
            .then(data => {
                const list = document.getElementById('feedbacks-list');
                list.innerHTML = '';
                
                if (!data || data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-comment-dots"></i>
                            <h3>暂无反馈</h3>
                            <p>还没有任何用户反馈</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(feedback => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">用户: ${feedback.username}</div>
                            <div class="card-date">${feedback.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${feedback.content}</p>
                        </div>
                        <div class="status-badge status-${feedback.status === 'pending' ? 'pending' : 'success'}">
                            ${feedback.status === 'pending' ? '待处理' : '已处理'}
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-primary" onclick="viewFeedbackDetail('${feedback.id}')">
                                <i class="fas fa-eye"></i> 查看详情
                            </button>
                        </div>
                    `;
                    list.appendChild(card);
                });
            })
            .catch(error => {
                console.error('加载反馈失败:', error);
                showNotification('加载失败', '无法加载用户反馈');
            });
    }

    // 加载管理员申请列表
    function loadAdminRequests() {
        console.log('加载管理员申请列表');
        
        fetch('/api/admin_requests')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('admin-requests-list');
                list.innerHTML = '';
                
                if (!data || data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-user-shield"></i>
                            <h3>暂无申请</h3>
                            <p>还没有任何管理员申请</p>
                        </div>
                    `;
                    return;
                }
                
                // 确保数据是数组
                if (!Array.isArray(data)) {
                    console.error('返回的数据不是数组:', data);
                    return;
                }
                
                data.forEach(request => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">用户: ${request.username}</div>
                            <div class="card-date">${request.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${request.reason}</p>
                        </div>
                        <div class="status-badge status-${request.status === 'pending' ? 'pending' : request.status === 'approved' ? 'success' : 'danger'}">
                            ${request.status === 'pending' ? '处理中' : request.status === 'approved' ? '已批准' : '已拒绝'}
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-success" onclick="approveAdminRequest('${request.id}')">
                                <i class="fas fa-check"></i> 批准
                            </button>
                            <button class="btn btn-danger" onclick="rejectAdminRequest('${request.id}')">
                                <i class="fas fa-times"></i> 拒绝
                            </button>
                        </div>
                    `;
                    list.appendChild(card);
                });
            })
            .catch(error => {
                console.error('加载管理员申请失败:', error);
                showNotification('加载失败', '无法加载管理员申请');
            });
    }

    // 加载问卷回答
    function loadSurveyResponses() {
        fetch('/api/survey_responses')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('survey-responses-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-comment-dots"></i>
                            <h3>暂无问卷回答</h3>
                            <p>还没有任何问卷回答</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(response => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">问卷: ${response.survey_title}</div>
                            <div class="card-date">${response.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${response.content}</p>
                        </div>
                        <div class="card-footer">
                            <p>用户: ${response.username}</p>
                        </div>
                    `;
                    list.appendChild(card);
                });
            })
            .catch(error => {
                console.error('加载问卷回答失败:', error);
                showNotification('加载失败', '无法加载问卷回答');
            });
    }

    // 发布公告
    document.getElementById('publish-announcement').addEventListener('click', function() {
        const title = document.getElementById('announcement-title').value;
        const content = document.getElementById('announcement-content').value;
        if (!title || !content) {
            showNotification('输入错误', '请填写公告标题和内容');
            return;
        }

        fetch('/api/announcements', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ title: title, content: content }),
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('发布公告成功', '公告已成功发布');
                document.getElementById('announcement-title').value = '';
                document.getElementById('announcement-content').value = '';
                loadAnnouncements();
            } else {
                showNotification('发布公告失败', data.message);
            }
        })
        .catch(error => {
            showNotification('发布公告失败', '无法连接到服务器，请稍后再试');
            console.error('Error:', error);
        });
    });

    // 发布问卷
    document.getElementById('publish-survey').addEventListener('click', function() {
        const title = document.getElementById('survey-title').value;
        const content = document.getElementById('survey-content').value;
        if (!title || !content) {
            showNotification('输入错误', '请填写问卷标题和内容');
            return;
        }

        fetch('/api/surveys', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ title: title, content: content }),
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('发布问卷成功', '问卷已成功发布');
                document.getElementById('survey-title').value = '';
                document.getElementById('survey-content').value = '';
                loadSurveys();
            } else {
                showNotification('发布问卷失败', data.message);
            }
        })
        .catch(error => {
            showNotification('发布问卷失败', '无法连接到服务器，请稍后再试');
            console.error('Error:', error);
        });
    });

    // 退出登录
    document.getElementById('logout-btn').addEventListener('click', function() {
        window.location.href = '/logout';
    });

    // 监听来自后端的实时消息
    socket.on('new_announcement', function(data) {
        showNotification('新公告发布', data.title);
        loadAnnouncements();
    });

    socket.on('new_survey', function(data) {
        showNotification('新问卷发布', data.title);
        loadSurveys();
    });

    socket.on('new_feedback', function(data) {
        showNotification('新用户反馈', '有用户提交了新反馈');
        loadFeedbacks();
    });

    socket.on('new_admin_request', function(data) {
        showNotification('新管理员申请', '有用户提交了管理员申请');
        loadAdminRequests();
    });

    socket.on('feedback_processed', function(data) {
        showNotification('反馈已处理', '反馈已收到回复');
        loadFeedbacks();
    });

    // 页面加载时初始化数据
    loadAnnouncements();
    loadSurveys();
    loadUsers();
    loadFeedbacks();
    loadAdminRequests();
});

// 删除公告
function deleteAnnouncement(announcementId) {
    fetch(`/api/announcements/${announcementId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('操作成功', '公告已删除');
            loadAnnouncements();
        } else {
            showNotification('操作失败', data.message);
        }
    })
    .catch(error => {
        showNotification('操作失败', '无法连接到服务器，请稍后再试');
        console.error('Error:', error);
    });
}

// 删除问卷
function deleteSurvey(surveyId) {
    fetch(`/api/surveys/${surveyId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('操作成功', '问卷已删除');
            loadSurveys();
        } else {
            showNotification('操作失败', data.message);
        }
    })
    .catch(error => {
        showNotification('操作失败', '无法连接到服务器，请稍后再试');
        console.error('Error:', error);
    });
}

// 删除用户
function deleteUser(userId) {
    fetch(`/api/users/${userId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('操作成功', '用户已删除');
            loadUsers();
        } else {
            showNotification('操作失败', data.message);
        }
    })
    .catch(error => {
        showNotification('操作失败', '无法连接到服务器，请稍后再试');
        console.error('Error:', error);
    });
}